/*
 * @Author: xiaosihan
 * @Date: 2024-10-08 22:04:08
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-10-20 18:35:36
 */

import adminApi from "@api/adminApi";
import loginApi from "@api/loginAPI";
import loginAPI from "@api/loginAPI";
import { UserData } from "@type";
import { get, isUndefined } from "lodash";
import { configure, observable } from "mobx";
configure({ enforceActions: "never" });

const adminStore = (window.adminStore = observable(
  {
    //用户id
    userId: "",
    // 用户名
    name: "用户名",
    //手机号码
    phone: "",
    //头像
    avatarUrl: "",
    //是否登录 undefined 为等待登录
    isLogin: undefined as boolean | undefined,
    //等待登录
    async awaitLogin() {
      while (!this.isLogin) {
        await new Promise((resolve) => setTimeout(resolve, 200));
      }
    },
    //等待登录状态
    async awaitLoginState() {
      while (isUndefined(this.isLogin)) {
        await new Promise((resolve) => setTimeout(resolve, 200));
      }
    },
    // 获取用户信息
    async getAdminUser() {
      if (localStorage.token) {
        const result = await loginAPI.get_user_info();
        const name = get(result, ["data", "data", "name"]);
        const Phone = get(result, ["data", "data", "phone"]);
        const id = get(result, ["data", "data", "id"]);
        const avatarUrl = get(result, ["data", "data", "avatarUrl"]);
        const success = get(result, ["data", "success"]);

        if (success) {
          this.userId = id;
          this.name = name;
          this.phone = Phone;
          this.avatarUrl = avatarUrl;
          this.isLogin = true;
        } else {
          this.isLogin = false;
        }
      } else {
        this.isLogin = false;
      }
    },

    //验证码登录
    async login(phone: string, password: string) {
      const result = (await adminApi.admin_login(phone, password)) as any;
      const name = get(result, ["data", "name"]);
      const id = get(result, ["data", "id"]);
      const Phone = get(result, ["data", "phone"]);
      const token = get(result, ["data", "token"]);
      const success = get(result, ["success"]);
      const message = get(result, ["message"]);
      if (success) {
        localStorage.token = token;
        this.userId = id;
        this.name = name;
        this.phone = Phone;
        this.isLogin = true;
        return "";
      } else {
        this.isLogin = false;
        return message;
      }
    },

    //退出登录
    loginOut() {
      loginApi.loginOut();
      localStorage.token = "";
      this.isLogin = false;
    },

    //修改用户信息
    async updateUser(userData: Partial<UserData>) {
      //   const res = await loginAPI.updateUser({ ...userData, id: this.userId });
      this.getAdminUser();
      return {};
    },
  },
  {},
  { deep: false }
));

export default adminStore;
